﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QLab.UX.Engine
{
    public class QLabFunction
    {
        public string Name { get; set; }
        public string Path
        {
            get
            {
                return this.ParentFolder == null ? this.ParentProject.HomeFolderPath : this.ParentFolder.Path + this.Name;
            }
        }
        public QLabFolder ParentFolder { get; set; }
        public QLabProject ParentProject { get; set; }
        public string Text { get; set; }
        public bool Changed { get; set; }

        public QLabFunction(QLabFolder parentFolder, QLabProject parentProject, string name)
        {
            this.ParentFolder = parentFolder;
            this.ParentProject = parentProject;
            this.Name = name;
            this.Text = this.Read();
            this.Changed = false;
        }

        public string Read()
        {
            return System.IO.File.ReadAllText(this.Path);
        }

        public void Save()
        {
            this.Changed = false;
            System.IO.File.WriteAllText(this.Path, this.Text);
            this.OnFunctionSaved();
        }

        public delegate void FunctionSavedEventHandler(object sender, FunctionSavedEventArgs e);
        public event FunctionSavedEventHandler FunctionSaved = null;
        private void OnFunctionSaved()
        {
            if (this.FunctionSaved != null)
                this.FunctionSaved(this, new FunctionSavedEventArgs(this));
        }

        public delegate void FunctionClosingEventHandler(object sender, FunctionSavedEventArgs e);
        public event FunctionClosingEventHandler FunctionClosing = null;
        private void OnFunctionClosing()
        {
            if (this.FunctionClosing != null)
                this.FunctionClosing(this, new FunctionSavedEventArgs(this));
        }

        public void Close()
        {
            this.OnFunctionClosing();
        }

        internal void SetText(string text)
        {
            this.Changed = true;
            this.Text = text;
        }
    }

    public class FunctionSavedEventArgs : EventArgs
    {
        public FunctionSavedEventArgs(QLabFunction function)
        {
            this.function = function;
        }

        private QLabFunction function;
        public QLabFunction Function
        {
            get { return this.function; }
        }
    }

    public class FunctionClosingEventArgs : EventArgs
    {
        public FunctionClosingEventArgs(QLabFunction function)
        {
            this.function = function;
        }

        private QLabFunction function;
        public QLabFunction Function
        {
            get { return this.function; }
        }
    }
}
